<?php


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Kingdee;

use app\crm\model\Customer;
use think\facade\Db;
use think\facade\Log;
use think\validate\ValidateRule;

class Kingdee
{
    private $king = [];

    private $customer = "";//客户id
    private $seller = "";//销售员id
    private $sale = "";//销售组织
    private $priceList = "";

    public function __construct($input = 0)
    {
        //金蝶传参使用账套id
        $this->king = config('kingdee.king');
        $gqshConf = config('kingdee.seller_sale');
        $this->customer = $gqshConf['customer'];
        $this->sale = $gqshConf['sale'];
        $this->priceList = $gqshConf['priceList'];
        $this->seller = $gqshConf['seller'];
    }

    /**
     * 销售出库单订单
     * @param $order_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function send_order($order_id)
    {
        $info = Db::name('shop_order')->where(['id' => $order_id])->find();
        if (!$info) {

            return ['code' => 1, 'msg' => '订单信息获取失败'];
        }

        //客户金蝶编码
        //$king_no='301.01.0325';
        $king_no = KingFunction::get_king_no($info['uid']);
        if ($king_no == '') {

            return ['code' => 1, 'msg' => '客户金蝶编码获取失败'];
        }


        //销售组织（市场编码）
        $sale_no = $info['sales_organization'];
        $settlement_no = $info['settlement_organization'];
        $shop_no = KingFunction::get_shop_no($info['shop_id']);
        if ($sale_no == '') {

            return ['code' => 1, 'msg' => '销售组织编码获取失败'];
        }
        if ($shop_no == '') {

            return ['code' => 1, 'msg' => '门店编码获取失败'];
        }
        if($shop_no == '302.02')
        {
            $customer = DB::name('customer')->where('id','=',$info['uid'])->find();
            if($customer['source_id'] == 597)
            {
                $shop_no = '302.04';
            }
        }
        //$sale_no='301';
        //销售部门（门店编码）
        // $shop_no='301.01';

        $data_model = "{
        \"FID\":0,
        \"FOwnerTypeIdHead\":\"BD_OwnerOrg\",
        \"FIsTotalServiceOrCost\":false,
    }";
        $setting = DB::name('setting')->cache(true,3600)->column('name','id');

        $setting = DB::name('setting')->cache(true,3600)->column('name','id');
        $king_goods = [];
        // 根据订单id查询该订单下所有的商品存储数据
        $info['order_goods'] = Db::name('shop_order_goods')
            ->where('order_id', $order_id)
            ->where('prestock_type','<>',3)
            ->field('id, number, pay_price, goods_price,is_project, goods_id, kingdee_code,unit_code,desc,is_gift,house_code,coupon_type,data_business_type,prestock_type,discount_amount,pay_amount,gift_amount')
            ->select()
            ->toArray();
        if($info['service_log_id']>0 ){
            $og_count = count($info['order_goods']);
        }else{


            $send_order_goods = [];
            $cjyh_amount = [];//冲减优惠价格
            $deduct_bj = $deduct_zj = [];
            foreach($info['order_goods'] as $k=>$v){
                if(in_array($v['prestock_type'],[1,3])){
                    if($v['goods_id'] != 170 && $v['is_project'] == 2){
                        array_push($send_order_goods,$v);
                        array_push($deduct_bj,$v['pay_amount']);
                        array_push($deduct_zj,$v['gift_amount']);
                        array_push($cjyh_amount,$v['discount_amount']);
                    }
                }
            }

            $cjyh_amount = bcadd(array_sum($cjyh_amount),0,2);
            if($cjyh_amount != 0){
                $cjyh_data = [
                    'number'=>$cjyh_amount <=0 ?-1:1,
                    'pay_price'=>abs($cjyh_amount),
                    'goods_price'=>'0',
                    'is_project'=>2,
                    'goods_id'=>170,
                    'kingdee_code'=>'101.12.098',
                    'unit_code'=>'ge',
                    'is_gift'=>0,
                    'house_code'=>$send_order_goods[0]['house_code'],
                    'coupon_type'=>0,
                    'data_business_type'=>0,
                    'desc'=>'冲减优惠'
                ];
                array_push($send_order_goods,$cjyh_data);
            }

            $info['order_goods'] = $send_order_goods;

            $og_count = count($info['order_goods']);

            $info['pay_amount'] = bcadd(array_sum($deduct_bj),0,2);
            $info['gift_amount'] = bcadd(array_sum($deduct_zj),0,2);
            $info['order_amount'] = bcadd($info['pay_amount'], $info['gift_amount'],2);

        }


        //判断是否推运行空 end
        for ($og_i = 0; $og_i < $og_count; $og_i++) {
            /*if ($info['order_goods'][$og_i]['coupon_type'] == 1)
            {
                continue;
            }*/
//            //商品-暂时注掉
//            if ($info['order_goods'][$og_i]['is_project']==1)
//            {
//                $king_goods[$og_i]['FRowType'] = "Standard";
//            }else
//            {
//                //服务
//                $king_goods[$og_i]['FRowType'] = "Service";
//            }
            $king_goods[$og_i]['FMaterialId']['FNumber'] = $info['order_goods'][$og_i]['kingdee_code']; // 商品金蝶编码
            $king_goods[$og_i]['FUnitID']['FNumber'] = $info['order_goods'][$og_i]['unit_code'];//销售单位
            $king_goods[$og_i]['FIsFree'] = $info['order_goods'][$og_i]['is_gift'] == 1 ? true : false;//是否赠品
            $king_goods[$og_i]['FOwnerTypeID'] = "BD_OwnerOrg";;
            $king_goods[$og_i]['FOwnerID']['FNumber'] = $settlement_no;//货主
            if ($info['order_goods'][$og_i]['kingdee_code'] !== '101.12.098')
            {
                $king_goods[$og_i]['FStockStatusID']['FNumber'] =  "KCZT01_SYS";
            }
            $king_goods[$og_i]['FStockId']['FNumber'] = $info['order_goods'][$og_i]['house_code'];//发货仓库编码
            $king_goods[$og_i]['FSalUnitID']['FNumber'] = $info['order_goods'][$og_i]['unit_code'];
            $king_goods[$og_i]['FEntrynote'] = $this->js_unescape($info['order_goods'][$og_i]['desc']);//备注
            $king_goods[$og_i]['FTaxPrice']=$info['order_goods'][$og_i]['pay_price'];//含税单价
            //商品
            if ($info['order_goods'][$og_i]['is_project']==1)
            {
                $king_goods[$og_i]['F_bzdj'] = $info['order_goods'][$og_i]['goods_price'];//商品取标准单价
            }else
            {
                $king_goods[$og_i]['F_bzdj'] = $info['order_goods'][$og_i]['pay_price'];//项目取销售单价
            }

            //$king_goods[$og_i]['F_bzje'] =bcmul($info['order_goods'][$og_i]['pay_price'],$info['order_goods'][$og_i]['number'],2) ;
            if ($info['order_goods'][$og_i]['coupon_type'] == 1)
            {
                $king_goods[$og_i]['FRealQty'] = -1;//商品数量
            }else{
                $king_goods[$og_i]['FRealQty'] = $info['order_goods'][$og_i]['number'];//商品数量
            }

            $king_goods[$og_i]['FPaySYCou'] = 0;//佣金未计价商品数量
            $king_goods[$og_i]['FSettleBySon'] = false;
        }
        // var_dump($king_goods);exit;
        $res = stripslashes($data_model);//字符串转义
        $arr = json_decode($res, true);
        $arr['Model']['FDate'] = date('Y-m-d', $info['deal_time']);//成交日期
        //$arr['Model']['FBillTypeID']['FNUMBER'] ='XSDD01_SYS';//单据类型:默认
        //$arr['Model']['FNote'] = "中台订单," . $this->js_unescape($info['description']);//备注
        $arr['Model']['FNote'] = $this->js_unescape($info['description']);//备注
        $arr['Model']['FSaleOrgId']['FNumber'] = $sale_no;//销售组织编码
        $arr['Model']['FCustomerID']['FNumber'] = $king_no;//客户编码
        $arr['Model']['FSaleDeptID']['FNumber'] = $shop_no;//门店编码
        $arr['Model']['FReceiveId']['FNumber'] = $king_no;//客户编码
        $arr['Model']['FStockOrgId']['FNumber'] = $settlement_no;//发货组织编码

        $arr['Model']['FDeliveryDeptID']['FNumber'] = $shop_no;//门店编码
        $arr['Model']['FSettleID']['FNumber'] = $king_no;//客户编码
        $arr['Model']['FPayerID']['FNumber'] = $king_no;//客户编码
        $arr['Model']['F_zsje'] = $info['gift_amount'];  //赠送金额
        $arr['Model']['F_xsje'] = $info['pay_amount'];  //销售金额
        $arr['Model']['F_ora_Text_qtr1'] = isset($setting[$info['source_id']])?$setting[$info['source_id']]:'';//客户来源
        $arr['Model']['F_ora_Amount_re5'] = $info['shop_transfer_amount'];  //店转金额
        $arr['Model']['F_hjje'] = $info['order_amount'];  //合计金额
        $arr['Model']['F_ora_cxzc']['FNumber'] = $info['sales_policy'] ? $info['sales_policy'] : '';//销售政策
        $arr['Model']['F_ora_ywlx']['FNumber'] = '0' . $info['business_type'];//业务类型
        $arr['Model']['F_ora_kdlx']['FNumber'] = '0' . $info['order_type'];//开单类型

        $arr['Model']['F_ora_Assistant']['FNumber'] = '0' . $info['income_type'];//收入类型
        $arr['Model']['F_ora_Text'] = '';  //小号
        $arr['Model']['SubHeadEntity']['FSettleOrgID']['FNumber'] = $sale_no;//销售组织编码
        //$arr['Model']['SubHeadEntity']['FSettleOrgID']['FNumber'] = $sale_no;//销售组织编码
        $arr['Model']['FDeliveryDeptID']['FNumber'] = $info['delivery_king'];//发货部门id
        $arr['Model']['FEntity'] = array_values($king_goods);

        //echo json_encode($arr);exit;
        $data = array(
            "SAL_OUTSTOCK",//业务对象标识FormId
            json_encode($arr)//具体Json字串
        );

        $param = $this->post();

        if ($param) {
            $post_content = KingFunction::create_postdata($data);
            $result = json_decode(KingFunction::invoke_save($param['url'], $post_content, $param['cook'],$param['session']), TRUE);
            if ($result['Result']['ResponseStatus']['IsSuccess']) {
                //成功处理
                $param = $result['Result']['ResponseStatus']['SuccessEntitys'][0];
                Db::name('shop_order')->where(['id' => $order_id])->update(['is_pay' => 1, 'pay_time' => time(), 'king_status' => 1, 'king_id' => $param['Id'], 'king_sale_no' => $param['Number'], 'king_push_time' => time(), 'status' => 2]);
                $errorMsg = 'king push success!';
                $this->addPushLog($info, 1, $errorMsg, $arr, $result);
                return ['code' => 0, 'msg' => '操作成功'];
            } else {
                // 订单下推失败 则记录该订单下推时的参数值
                $errorMsg = $result['Result']['ResponseStatus']['Errors'][0]['Message'];

                return ['code' => 1, 'msg' => $errorMsg];
            }
        } else {

            return ['code' => 1, 'msg' => '金蝶账号登录失败'];
        }
    }


    /**
     * 销售出库单订单-核销产生的订单/出预存货的订单
     * @param $order_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function send_service_prestock_order($order_id)
    {
        $info = Db::name('shop_order')->where(['id' => $order_id])->find();
        if (!$info) {
            return ['code' => 1, 'msg' => '订单信息获取失败'];
        }

        //客户金蝶编码
        //$king_no='301.01.0325';
        $king_no = KingFunction::get_king_no($info['uid']);
        if ($king_no == '') {
            return ['code' => 1, 'msg' => '客户金蝶编码获取失败'];
        }


        //销售组织（市场编码）
        $sale_no = $info['sales_organization'];
        $settlement_no = $info['settlement_organization'];
        $shop_no = KingFunction::get_shop_no($info['shop_id']);
        if ($sale_no == '') {

            return ['code' => 1, 'msg' => '销售组织编码获取失败'];
        }
        if ($shop_no == '') {

            return ['code' => 1, 'msg' => '门店编码获取失败'];
        }
        if($shop_no == '302.02')
        {
            $customer = DB::name('customer')->where('id','=',$info['uid'])->find();
            if($customer['source_id'] == 597)
            {
                $shop_no = '302.04';
            }
        }
        //$sale_no='301';
        //销售部门（门店编码）
        // $shop_no='301.01';

        $data_model = "{
        \"FID\":0,
        \"FOwnerTypeIdHead\":\"BD_OwnerOrg\",
        \"FIsTotalServiceOrCost\":false,
    }";
        $setting = DB::name('setting')->cache(true,3600)->column('name','id');

        $king_goods = [];
        // 根据订单id查询该订单下所有的商品存储数据
        $info['order_goods'] = Db::name('shop_order_goods')
            ->where('order_id', $order_id)
            ->field('id, number, pay_price, goods_price,is_project, goods_id, kingdee_code,unit_code,desc,is_gift,house_code,coupon_type,data_business_type,prestock_type,discount_amount,pay_amount,gift_amount')
            ->select()
            ->toArray();

        $og_count = count($info['order_goods']);

        //判断是否推运行空 end
        for ($og_i = 0; $og_i < $og_count; $og_i++) {
            /*if ($info['order_goods'][$og_i]['coupon_type'] == 1)
            {
                continue;
            }*/
//            //商品-暂时注掉
//            if ($info['order_goods'][$og_i]['is_project']==1)
//            {
//                $king_goods[$og_i]['FRowType'] = "Standard";
//            }else
//            {
//                //服务
//                $king_goods[$og_i]['FRowType'] = "Service";
//            }
            $king_goods[$og_i]['FMaterialId']['FNumber'] = $info['order_goods'][$og_i]['kingdee_code']; // 商品金蝶编码
            $king_goods[$og_i]['FUnitID']['FNumber'] = $info['order_goods'][$og_i]['unit_code'];//销售单位
            $king_goods[$og_i]['FIsFree'] = $info['order_goods'][$og_i]['is_gift'] == 1 ? true : false;//是否赠品
            $king_goods[$og_i]['FOwnerTypeID'] = "BD_OwnerOrg";;
            $king_goods[$og_i]['FOwnerID']['FNumber'] = $settlement_no;//货主
            if ($info['order_goods'][$og_i]['kingdee_code'] !== '101.12.098')
            {
                $king_goods[$og_i]['FStockStatusID']['FNumber'] =  "KCZT01_SYS";
            }
            $king_goods[$og_i]['FStockId']['FNumber'] = $info['order_goods'][$og_i]['house_code'];//发货仓库编码
            $king_goods[$og_i]['FSalUnitID']['FNumber'] = $info['order_goods'][$og_i]['unit_code'];
            $king_goods[$og_i]['FEntrynote'] = $this->js_unescape($info['order_goods'][$og_i]['desc']);//备注
            $king_goods[$og_i]['FTaxPrice']=$info['order_goods'][$og_i]['pay_price'];//含税单价
            //商品
            if ($info['order_goods'][$og_i]['is_project']==1)
            {
                $king_goods[$og_i]['F_bzdj'] = $info['order_goods'][$og_i]['goods_price'];//商品取标准单价
            }else
            {
                $king_goods[$og_i]['F_bzdj'] = $info['order_goods'][$og_i]['pay_price'];//项目取销售单价
            }

            //$king_goods[$og_i]['F_bzje'] =bcmul($info['order_goods'][$og_i]['pay_price'],$info['order_goods'][$og_i]['number'],2) ;
            if ($info['order_goods'][$og_i]['coupon_type'] == 1)
            {
                $king_goods[$og_i]['FRealQty'] = -1;//商品数量
            }else{
                $king_goods[$og_i]['FRealQty'] = $info['order_goods'][$og_i]['number'];//商品数量
            }

            $king_goods[$og_i]['FPaySYCou'] = 0;//佣金未计价商品数量
            $king_goods[$og_i]['FSettleBySon'] = false;
        }
        // var_dump($king_goods);exit;
        $res = stripslashes($data_model);//字符串转义
        $arr = json_decode($res, true);
        $arr['Model']['FDate'] = date('Y-m-d', $info['deal_time']);//成交日期
        //$arr['Model']['FBillTypeID']['FNUMBER'] ='XSDD01_SYS';//单据类型:默认
        //$arr['Model']['FNote'] = "中台订单," . $this->js_unescape($info['description']);//备注
        $arr['Model']['FNote'] = $this->js_unescape($info['description']);//备注
        $arr['Model']['FSaleOrgId']['FNumber'] = $sale_no;//销售组织编码
        $arr['Model']['FCustomerID']['FNumber'] = $king_no;//客户编码
        $arr['Model']['FSaleDeptID']['FNumber'] = $shop_no;//门店编码
        $arr['Model']['FReceiveId']['FNumber'] = $king_no;//客户编码
        $arr['Model']['FStockOrgId']['FNumber'] = $settlement_no;//发货组织编码

        $arr['Model']['FDeliveryDeptID']['FNumber'] = $shop_no;//门店编码
        $arr['Model']['FSettleID']['FNumber'] = $king_no;//客户编码
        $arr['Model']['FPayerID']['FNumber'] = $king_no;//客户编码
        $arr['Model']['F_zsje'] = $info['gift_amount'];  //赠送金额
        $arr['Model']['F_xsje'] = $info['pay_amount'];  //销售金额
        $arr['Model']['F_ora_Text_qtr1'] = isset($setting[$info['source_id']])?$setting[$info['source_id']]:'';//客户来源
        $arr['Model']['F_ora_Amount_re5'] = $info['shop_transfer_amount'];  //店转金额
        $arr['Model']['F_hjje'] = $info['order_amount'];  //合计金额
        $arr['Model']['F_ora_cxzc']['FNumber'] = $info['sales_policy'] ? $info['sales_policy'] : '';//销售政策
        $arr['Model']['F_ora_ywlx']['FNumber'] = '0' . $info['business_type'];//业务类型
        $arr['Model']['F_ora_kdlx']['FNumber'] = '0' . $info['order_type'];//开单类型

        $arr['Model']['F_ora_Assistant']['FNumber'] = '0' . $info['income_type'];//收入类型
        $arr['Model']['F_ora_Text'] = '';  //小号
        $arr['Model']['SubHeadEntity']['FSettleOrgID']['FNumber'] = $sale_no;//销售组织编码
        //$arr['Model']['SubHeadEntity']['FSettleOrgID']['FNumber'] = $sale_no;//销售组织编码
        $arr['Model']['FDeliveryDeptID']['FNumber'] = $info['delivery_king'];//发货部门id
        $arr['Model']['FEntity'] = array_values($king_goods);

        //echo json_encode($arr);exit;
        $data = array(
            "SAL_OUTSTOCK",//业务对象标识FormId
            json_encode($arr)//具体Json字串
        );

        $param = $this->post();

        if ($param) {
            $post_content = KingFunction::create_postdata($data);
            $result = json_decode(KingFunction::invoke_save($param['url'], $post_content, $param['cook'],$param['session']), TRUE);
            if ($result['Result']['ResponseStatus']['IsSuccess']) {
                //成功处理
                $param = $result['Result']['ResponseStatus']['SuccessEntitys'][0];
                Db::name('shop_order')->where(['id' => $order_id])->update(['is_pay' => 1, 'pay_time' => time(), 'king_status' => 1, 'king_id' => $param['Id'], 'king_sale_no' => $param['Number'], 'king_push_time' => time(), 'status' => 2]);
                $errorMsg = 'king push success!';
                $this->addPushLog($info, 1, $errorMsg, $arr, $result);
                return ['code' => 0, 'msg' => '操作成功'];
            } else {
                // 订单下推失败 则记录该订单下推时的参数值
                $errorMsg = $result['Result']['ResponseStatus']['Errors'][0]['Message'];

                return ['code' => 1, 'msg' => $errorMsg];
            }
        } else {

            return ['code' => 1, 'msg' => '金蝶账号登录失败'];
        }
    }

    /**
     * 销售出库单订单-病例开单拆出来的出库单
     * @param $order_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */

    public function send_case_order($order_id)
    {
        $info = Db::name('shop_order')->where(['id' => $order_id])->find();
        if (!$info) {

            return ['code' => 1, 'msg' => '订单信息获取失败'];
        }

        //客户金蝶编码
        //$king_no='301.01.0325';
        $king_no = KingFunction::get_king_no($info['uid']);
        if ($king_no == '') {

            return ['code' => 1, 'msg' => '客户金蝶编码获取失败'];
        }


        //销售组织（市场编码）
        $sale_no = $info['sales_organization'];
        $settlement_no = $info['settlement_organization'];
        $shop_no = KingFunction::get_shop_no($info['shop_id']);
        if ($sale_no == '') {

            return ['code' => 1, 'msg' => '销售组织编码获取失败'];
        }
        if ($shop_no == '') {

            return ['code' => 1, 'msg' => '门店编码获取失败'];
        }
        if($shop_no == '302.02')
        {
            $customer = DB::name('customer')->where('id','=',$info['uid'])->find();
            if($customer['source_id'] == 597)
            {
                $shop_no = '302.04';
            }
        }
        //$sale_no='301';
        //销售部门（门店编码）
        // $shop_no='301.01';

        $data_model = "{
        \"FID\":0,
        \"FOwnerTypeIdHead\":\"BD_OwnerOrg\",
        \"FIsTotalServiceOrCost\":false,
    }";
        $setting = DB::name('setting')->cache(true,3600)->column('name','id');

        $setting = DB::name('setting')->cache(true,3600)->column('name','id');
        $king_goods = [];
        // 根据订单id查询该订单下所有的商品存储数据
        $info['order_goods'] = Db::name('shop_order_goods')
            ->where('order_id', $order_id)
            ->where('kingdee_code','<>','101.12.098')
            ->field('id, number, pay_price, goods_price,is_project, goods_id, kingdee_code,unit_code,desc,is_gift,house_code,coupon_type,data_business_type,prestock_type,discount_amount,pay_amount,gift_amount')
            ->select()
            ->toArray();

        if($info['service_log_id']>0 ){
            $og_count = count($info['order_goods']);
        }else{
            $is_project  = array_column( $info['order_goods'],'is_project');
            $send_order_goods = [];
            $cjyh_amount = [];//冲减优惠价格
            $deduct_bj = $deduct_zj = [];
            foreach($info['order_goods'] as $k=>$v){

                if(in_array($v['prestock_type'],[0,1,3])){
                    if($v['kingdee_code'] != '101.12.098' && $v['is_project'] == 2){
                        array_push($send_order_goods,$v);
                        array_push($deduct_bj,$v['pay_amount']);
                        array_push($deduct_zj,$v['gift_amount']);
                        array_push($cjyh_amount,$v['discount_amount']);
                    }
                }
            }

            $cjyh_amount = bcadd(array_sum($cjyh_amount),0,2);
            if($cjyh_amount != 0){
                $cjyh_data = [
                    'number'=>$cjyh_amount <=0 ?-1:1,
                    'pay_price'=>abs($cjyh_amount),
                    'goods_price'=>'0',
                    'is_project'=>2,
                    'goods_id'=>170,
                    'kingdee_code'=>'101.12.098',
                    'unit_code'=>'ge',
                    'is_gift'=>0,
                    'house_code'=>$send_order_goods[0]['house_code'],
                    'coupon_type'=>0,
                    'data_business_type'=>0,
                    'desc'=>'冲减优惠'
                ];
                array_push($send_order_goods,$cjyh_data);
            }

            $info['order_goods'] = $send_order_goods;

            $og_count = count($info['order_goods']);

            $info['pay_amount'] = bcadd(array_sum($deduct_bj),0,2);
            $info['gift_amount'] = bcadd(array_sum($deduct_zj),0,2);
            $info['order_amount'] = bcadd($info['pay_amount'], $info['gift_amount'],2);

        }


        if(empty($info['order_goods'])){
            return ['code' => 0, 'msg' => '操作成功.'];
        }


        //判断是否推运行空 end
        for ($og_i = 0; $og_i < $og_count; $og_i++) {
            /*if ($info['order_goods'][$og_i]['coupon_type'] == 1)
            {
                continue;
            }*/
//            //商品-暂时注掉
//            if ($info['order_goods'][$og_i]['is_project']==1)
//            {
//                $king_goods[$og_i]['FRowType'] = "Standard";
//            }else
//            {
//                //服务
//                $king_goods[$og_i]['FRowType'] = "Service";
//            }
            $king_goods[$og_i]['FMaterialId']['FNumber'] = $info['order_goods'][$og_i]['kingdee_code']; // 商品金蝶编码
            $king_goods[$og_i]['FUnitID']['FNumber'] = $info['order_goods'][$og_i]['unit_code'];//销售单位
            $king_goods[$og_i]['FIsFree'] = $info['order_goods'][$og_i]['is_gift'] == 1 ? true : false;//是否赠品
            $king_goods[$og_i]['FOwnerTypeID'] = "BD_OwnerOrg";;
            $king_goods[$og_i]['FOwnerID']['FNumber'] = $settlement_no;//货主
            if ($info['order_goods'][$og_i]['kingdee_code'] !== '101.12.098')
            {
                $king_goods[$og_i]['FStockStatusID']['FNumber'] =  "KCZT01_SYS";
            }
            $king_goods[$og_i]['FStockId']['FNumber'] = $info['order_goods'][$og_i]['house_code'];//发货仓库编码
            $king_goods[$og_i]['FSalUnitID']['FNumber'] = $info['order_goods'][$og_i]['unit_code'];
            $king_goods[$og_i]['FEntrynote'] = $this->js_unescape($info['order_goods'][$og_i]['desc']);//备注
            $king_goods[$og_i]['FTaxPrice']=$info['order_goods'][$og_i]['pay_price'];//含税单价
            //商品
            if ($info['order_goods'][$og_i]['is_project']==1)
            {
                $king_goods[$og_i]['F_bzdj'] = $info['order_goods'][$og_i]['goods_price'];//商品取标准单价
            }else
            {
                $king_goods[$og_i]['F_bzdj'] = $info['order_goods'][$og_i]['pay_price'];//项目取销售单价
            }

            //$king_goods[$og_i]['F_bzje'] =bcmul($info['order_goods'][$og_i]['pay_price'],$info['order_goods'][$og_i]['number'],2) ;
            if ($info['order_goods'][$og_i]['coupon_type'] == 1)
            {
                $king_goods[$og_i]['FRealQty'] = -1;//商品数量
            }else{
                $king_goods[$og_i]['FRealQty'] = $info['order_goods'][$og_i]['number'];//商品数量
            }

            $king_goods[$og_i]['FPaySYCou'] = 0;//佣金未计价商品数量
            $king_goods[$og_i]['FSettleBySon'] = false;
        }
        // var_dump($king_goods);exit;
        $res = stripslashes($data_model);//字符串转义
        $arr = json_decode($res, true);
        $arr['Model']['FDate'] = date('Y-m-d', $info['deal_time']);//成交日期
        //$arr['Model']['FBillTypeID']['FNUMBER'] ='XSDD01_SYS';//单据类型:默认
        //$arr['Model']['FNote'] = "中台订单," . $this->js_unescape($info['description']);//备注
        $arr['Model']['FNote'] = $this->js_unescape($info['description']);//备注
        $arr['Model']['FSaleOrgId']['FNumber'] = $sale_no;//销售组织编码
        $arr['Model']['FCustomerID']['FNumber'] = $king_no;//客户编码
        $arr['Model']['FSaleDeptID']['FNumber'] = $shop_no;//门店编码
        $arr['Model']['FReceiveId']['FNumber'] = $king_no;//客户编码
        $arr['Model']['FStockOrgId']['FNumber'] = $settlement_no;//发货组织编码

        $arr['Model']['FDeliveryDeptID']['FNumber'] = $shop_no;//门店编码
        $arr['Model']['FSettleID']['FNumber'] = $king_no;//客户编码
        $arr['Model']['FPayerID']['FNumber'] = $king_no;//客户编码
        $arr['Model']['F_zsje'] = $info['gift_amount'];  //赠送金额
        $arr['Model']['F_xsje'] = $info['pay_amount'];  //销售金额
        $arr['Model']['F_ora_Text_qtr1'] = isset($setting[$info['source_id']])?$setting[$info['source_id']]:'';//客户来源
        $arr['Model']['F_ora_Amount_re5'] = $info['shop_transfer_amount'];  //店转金额
        $arr['Model']['F_hjje'] = $info['order_amount'];  //合计金额
        $arr['Model']['F_ora_cxzc']['FNumber'] = $info['sales_policy'] ? $info['sales_policy'] : '';//销售政策
        $arr['Model']['F_ora_ywlx']['FNumber'] = '0' . $info['business_type'];//业务类型
        $arr['Model']['F_ora_kdlx']['FNumber'] = '0' . $info['order_type'];//开单类型

        $arr['Model']['F_ora_Assistant']['FNumber'] = '0' . $info['income_type'];//收入类型
        $arr['Model']['F_ora_Text'] = '';  //小号
        $arr['Model']['SubHeadEntity']['FSettleOrgID']['FNumber'] = $sale_no;//销售组织编码
        //$arr['Model']['SubHeadEntity']['FSettleOrgID']['FNumber'] = $sale_no;//销售组织编码
        $arr['Model']['FDeliveryDeptID']['FNumber'] = $info['delivery_king'];//发货部门id
        $arr['Model']['FEntity'] = array_values($king_goods);

        //echo json_encode($arr);exit;
        $data = array(
            "SAL_OUTSTOCK",//业务对象标识FormId
            json_encode($arr)//具体Json字串
        );

        $param = $this->post();

        if ($param) {
            $post_content = KingFunction::create_postdata($data);
            $result = json_decode(KingFunction::invoke_save($param['url'], $post_content, $param['cook'],$param['session']), TRUE);
            if ($result['Result']['ResponseStatus']['IsSuccess']) {
                //成功处理
                $param = $result['Result']['ResponseStatus']['SuccessEntitys'][0];
                Db::name('shop_order')->where(['id' => $order_id])->update(['is_pay' => 1, 'pay_time' => time(), 'king_status' => 1, 'king_id' => $param['Id'], 'king_sale_no' => $param['Number'], 'king_push_time' => time(), 'status' => 2]);
                $errorMsg = 'king push success!';
                $this->addPushLog($info, 1, $errorMsg, $arr, $result);
                return ['code' => 0, 'msg' => '操作成功'];
            } else {
                // 订单下推失败 则记录该订单下推时的参数值
                $errorMsg = $result['Result']['ResponseStatus']['Errors'][0]['Message'];

                return ['code' => 1, 'msg' => $errorMsg];
            }
        } else {

            return ['code' => 1, 'msg' => '金蝶账号登录失败'];
        }
    }



    /**
     * 退款单接口
     * @param $order_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function refund_money($order_id)
    {
        $info = Db::name('shop_refund_order')->where(['id' => $order_id])->find();
        if (!$info) {

            return ['code' => 1, 'msg' => '订单信息获取失败'];
        }

        if($info['type'] == '3' && $info['is_pay'] == '1'){

            return ['code' => 1, 'msg' => '该订单已经支付成功，请勿重复推送！'];
        }

        //客户金蝶编码
        //$king_no='301.01.0325';
        $king_no = KingFunction::get_king_no($info['uid']);
        if ($king_no == '') {

            return ['code' => 1, 'msg' => '客户金蝶编码获取失败'];
        }

        $setting = DB::name('setting')->cache(true,3600)->column('name','id');

        //销售组织（市场编码）
        $sale_no = $info['sales_organization'];
        $settlement_no = $info['settlement_organization'];
        $shop_no = KingFunction::get_shop_no($info['shop_id']);
        if ($sale_no == '') {

            return ['code' => 1, 'msg' => '退款组织编码获取失败'];
        }
        if ($shop_no == '') {

            return ['code' => 1, 'msg' => '门店编码获取失败'];
        }
        if($shop_no == '302.02')
        {
            $customer = DB::name('customer')->where('id','=',$info['uid'])->find();
            if($customer['source_id'] == 597)
            {
                $shop_no = '302.04';
            }
        }


        $data_model = "{
    \"NeedUpDateFields\": [],
    \"NeedReturnFields\": [],
    \"IsDeleteEntry\": \"true\",
    \"SubSystemId\": \"\",
    \"IsVerifyBaseDataField\": \"false\",
    \"IsEntryBatchFill\": \"true\",
    \"ValidateFlag\": \"true\",
    \"NumberSearch\": \"true\",
    \"IsAutoAdjustField\": \"false\",
    \"InterationFlags\": \"\",
    \"IgnoreInterationFlag\": \"\",
    \"Model\": {
        \"FID\": 0,
        \"FBillTypeID\": {
            \"FNUMBER\": \"SKTKDLX01_SYS\"
        },
        \"FDATE\": \"\",
        \"FCONTACTUNITTYPE\": \"BD_Customer\",
        \"FISINIT\": false,
        \"FSETTLERATE\": 1.0,
        \"FDOCUMENTSTATUS\": \"Z\",
        \"FRECTUNITTYPE\": \"BD_Customer\",
        \"FCURRENCYID\": {
            \"FNumber\": \"PRE001\"
        },
        \"FSETTLEORGID\": {
            \"FNumber\": \"\"
        },
        \"FSALEORGID\": {
            \"FNumber\": \"\"
        },
        \"FBUSINESSTYPE\": \"1\",
        \"FEXCHANGERATE\": 1.0,
        \"FCancelStatus\": \"A\",
        \"FPAYORGID\": {
            \"FNumber\": \"\"
        },
        \"FISSAMEORG\": true,
        \"FSETTLECUR\": {
            \"FNUMBER\": \"PRE001\"
        },
        \"FISB2C\": false,
        \"FIsWriteOff\": false,
        \"FISCARRYRATE\": false,
        \"FSETTLEMAINBOOKID\": {
            \"FNUMBER\": \"PRE001\"
        },
        \"F_ora_cxzc\": {
            \"FNumber\": \"\"
        },
        \"F_ora_kdlx\": {
            \"FNumber\": \"01\"
        },
        \"F_ora_tklx\": {
            \"FNumber\": \"\"
        },
       
        \"FVirIsSameAcctOrg\": false,
        \"F_ora_Text_qtr\": \"\",
    }
}";

        $res = stripslashes($data_model);//字符串转义
        $arr = json_decode($res, true);
        $arr['Model']['FDate'] = date('Y-m-d', $info['deal_time']);//成交日期
        $arr['Model']['FCONTACTUNIT']['FNumber'] = $king_no;//客户编码
        $arr['Model']['FRECTUNIT']['FNumber'] = $king_no;//客户编码
        $arr['Model']['FBookingDate'] = date('Y-m-d', $info['deal_time']);//成交日期
        $arr['Model']['FSETTLEORGID']['FNumber'] = $sale_no;//结算组织
        $arr['Model']['FSALEORGID']['FNumber'] = $sale_no;//销售组织
        $arr['Model']['FSALEDEPTID']['FNumber'] = $shop_no;//门店编码
        $arr['Model']['FPAYORGID']['FNumber'] = $settlement_no;//付款组织
        $arr['Model']['F_ora_cxzc']['FNumber'] = $info['sales_policy'];//促销政策
        $arr['Model']['F_ora_kdlx']['FNumber'] = '0' . $info['order_type'];//开单类型
        $arr['Model']['F_ora_tklx']['FNumber'] = $info['refund_type'];//退款类型
        $arr['Model']['F_ora_Text_qtr'] = isset($setting[$info['source_id']])?$setting[$info['source_id']]:'';//客户来源
        $arr['Model']['FREMARK'] = $this->js_unescape($info['description']);//备注
        if ($info['combo'])
        {
            $arr['Model']['F_ora_Combo'] = $info['combo'];//1项目退款 2疤痕退款
        }
        $res=0;
        if ($settlement_no !== $sale_no)
        {
            $res=1;
        }
        //需修改为代码获取
        $king_goods = [];


        $info['refund_order_goods'] = Db::name('shop_refund_order_goods')
            ->where('order_id', $order_id)
            ->field('id, refund_mode, bank_number,data_business_type,data_sales_policy, descs,pay_price,gift_price,shop_transfer_price')
            ->select()
            ->toArray();
        $og_count = count($info['refund_order_goods']);

        for ($og_i = 0; $og_i < $og_count; $og_i++) {
            $king_goods[$og_i]['FSETTLETYPEID']['FNumber'] = $info['refund_order_goods'][$og_i]['refund_mode'];//结算方式
            $king_goods[$og_i]['FPURPOSEID']['FNumber'] = "SFKYT01_SYS";//原收款用途 SFKYT01_SYS 销售收款  SFKYT02_SYS 预收款
            $king_goods[$og_i]['FREFUNDAMOUNTFOR'] = bcadd(bcadd($info['refund_order_goods'][$og_i]['pay_price'], $info['refund_order_goods'][$og_i]['gift_price'], 2),$info['refund_order_goods'][$og_i]['shop_transfer_price'],2);//应退金额
            $king_goods[$og_i]['F_ora_zsjebt'] = $info['refund_order_goods'][$og_i]['gift_price'];//应退赠金
            $king_goods[$og_i]['F_ora_Amount_83g'] = $info['refund_order_goods'][$og_i]['shop_transfer_price'];//应退店转

            $king_goods[$og_i]['FACCOUNTID']['FNumber'] = $info['refund_order_goods'][$og_i]['bank_number'];;//我方银行账号 除了现金和店转 必填
            $king_goods[$og_i]['FNOTE'] = $this->js_unescape($info['refund_order_goods'][$og_i]['descs']);//退款单备注必填
            $king_goods[$og_i]['F_ora_Aywlx']['FNumber'] = '0' . $info['refund_order_goods'][$og_i]['data_business_type'];//业务类型编码
            $king_goods[$og_i]['F_ora_Acxzc']['FNumber'] = $info['refund_order_goods'][$og_i]['data_sales_policy'];//促销政策编码
            if ($res & $sale_no=='403')
            {
                $king_goods[$og_i]['FINNERACCOUNTID']['FNUMBER'] ='888';//成都市场内部账号
            }
            if ($res & $sale_no=='401')
            {
                $king_goods[$og_i]['FINNERACCOUNTID']['FNUMBER'] ='666';//重庆市场内部账号
            }
        }
        $arr['Model']['FREFUNDBILLENTRY'] = $king_goods;
        $data = array(
            "AR_REFUNDBILL",//业务对象标识FormId
            json_encode($arr)//具体Json字串
        );
        //print_r(json_encode($arr));
        $param = $this->post();

        if ($param) {
            $post_content = KingFunction::create_postdata($data);
            $result = json_decode(KingFunction::invoke_save($param['url'], $post_content, $param['cook'], $param['session']), TRUE);
            if ($result['Result']['ResponseStatus']['IsSuccess']) {
                //成功处理
                $param = $result['Result']['ResponseStatus']['SuccessEntitys'][0];
                Db::name('shop_refund_order')->where(['id' => $order_id])->update(['king_status' => 1, 'king_id' => $param['Id'], 'king_num' => $param['Number'], 'king_push_time' => time(), 'status' => 2]);

                return ['code' => 0, 'msg' => '操作成功'];
            } else {
                // 订单下推失败 则记录该订单下推时的参数值
                $errorMsg = $result['Result']['ResponseStatus']['Errors'][0]['Message'];

                return ['code' => 1, 'msg' => $errorMsg];
            }
        } else {


            return ['code' => 1, 'msg' => '金蝶账号登录失败'];
        }

    }


    /**
     * 销售退货单接口
     * @param $order_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function refund_goods($order_id)
    {
        $info = Db::name('shop_refund_order')->where(['id' => $order_id])->find();
        if (!$info) {
            return ['code' => 1, 'msg' => '订单信息获取失败'];
        }

        //客户金蝶编码
        //$king_no='301.01.0325';
        $king_no = KingFunction::get_king_no($info['uid']);
        if ($king_no == '') {
            return ['code' => 1, 'msg' => '客户金蝶编码获取失败'];
        }


        $setting = DB::name('setting')->cache(true,3600)->column('name','id');
        //销售组织（市场编码）
        $sale_no = $info['sales_organization'];
        $settlement_no = $info['settlement_organization'];
        $shop_no = KingFunction::get_shop_no($info['shop_id']);
        if ($sale_no == '') {

            return ['code' => 1, 'msg' => '退款组织编码获取失败'];
        }
        if ($shop_no == '') {
            return ['code' => 1, 'msg' => '门店编码获取失败'];
        }
        if($shop_no == '302.02')
        {
            $customer = DB::name('customer')->where('id','=',$info['uid'])->find();
            if($customer['source_id'] == 597)
            {
                $shop_no = '302.04';
            }
        }

        $data_model = "{
	\"NeedUpDateFields\": [],
	\"NeedReturnFields\": [],
	\"IsDeleteEntry\": \"true\",
	\"SubSystemId\": \"\",
	\"IsVerifyBaseDataField\": \"false\",
	\"IsEntryBatchFill\": \"true\",
	\"ValidateFlag\": \"true\",
	\"NumberSearch\": \"true\",
	\"IsAutoAdjustField\": \"false\",
	\"InterationFlags\": \"\",
	\"IgnoreInterationFlag\": \"\",
	\"Model\": {
		\"FID\": 0,
		\"FBillTypeID\": {
			\"FNUMBER\": \"XSTHD01_SYS\"
		},
		\"FDate\": \"\",
		\"FSaleOrgId\": {
			\"FNumber\": \"\"
		},
		\"FRetcustId\": {
			\"FNumber\": \"\"
		},
		\"FSaledeptid\": {
			\"FNumber\": \"\"
		},
		\"FReturnReason\": {
			\"FNumber\": \"\"
		},
		\"FTransferBizType\": {
			\"FNumber\": \"OverOrgSal\"
		},
		\"FStockOrgId\": {
			\"FNumber\": \"\"
		},
		\"FStockDeptId\": {
			\"FNumber\": \"\"
		},
		\"FReceiveCustId\": {
			\"FNumber\": \"\"
		},
		\"FSettleCustId\": {
			\"FNumber\": \"\"
		},
		\"FPayCustId\": {
			\"FNumber\": \"\"
		},
		
		\"F_ora__zsje_re5\": \"\",
		\"F_ora_Amount_apv_83g\": \"\",
		\"F_ora__xsje_qtr\": \"\",
		\"F_ora__hjje_apv\": \"\",
		\"F_ora_Assistant_qtr\": {
			\"FNumber\": \"\"
		},
		
		\"F_ora__zsje_re5_fg2\": \"\",
		\"F_ora_Amount_apv_83g_uky\": \"\",
		\"F_ora__xsje_qtr_ca9\": \"\",
		\"F_ora__hjje_apv_dvn\": \"\",
		\"F_ora_Assistant_83g\": {
			\"FNumber\": \"\"
		},
		
		\"FOwnerTypeIdHead\": \"BD_OwnerOrg\",
		\"FIsTotalServiceOrCost\": false,
		\"F_zsje\": \"\",
		\"F_xsje\": \"\",
		\"F_hjje\": \"\",
		\"F_ora_Text_83g1\": \"\",
		\"F_ora_cxzc\": {
			\"FNumber\": \"\"
		},
		\"F_ora_ywlx\": {
			\"FNumber\": \"\"
		},
		\"F_ora_kdlx\": {
			\"FNumber\": \"\"
		},
		
		\"F_ora_Assistant\": {
		
			\"FNumber\": \"\"
		
		},
		\"SubHeadEntity\": {
			\"FSettleCurrId\": {
				\"FNumber\": \"PRE001\"
			},
			\"FSettleOrgId\": {
				\"FNumber\": \"\"
			},
			\"FLocalCurrId\": {
				\"FNumber\": \"PRE001\"
			},
			\"FExchangeTypeId\": {
				\"FNumber\": \"HLTX01_SYS\"
			},
			\"FExchangeRate\": 1.0
		}

	}
}";

        $res = stripslashes($data_model);//字符串转义
        $arr = json_decode($res, true);
        $arr['Model']['FDate'] = date('Y-m-d', $info['deal_time']);//成交日期
        $arr['Model']['FSaleOrgId']['FNumber'] = $sale_no;//销售组织
        $arr['Model']['FRetcustId']['FNumber'] = $king_no;//客户编码
        $arr['Model']['FSaledeptid']['FNumber'] = $shop_no;//销售门店编码
        $arr['Model']['FReturnReason']['FNumber'] = '';//退款原因编码 需修改为代码获取
        $arr['Model']['FStockOrgId']['FNumber'] = $settlement_no;//库存组织
        $arr['Model']['FStockDeptId']['FNumber'] = $shop_no;//门店编码
        $arr['Model']['F_ora_Text_83g1'] = isset($setting[$info['source_id']])?$setting[$info['source_id']]:'';//客户来源
        $arr['Model']['F_zsje'] = $info['gift_amount'];  //赠送金额
        $arr['Model']['F_xsje'] = $info['pay_amount'];  //销售金额 shop_transfer_amount

        $arr['Model']['F_ora_Amount_apv'] = $info['shop_transfer_amount'];  //店转金额
        $arr['Model']['F_hjje'] = $info['total_amount'];  //合计金额




        $arr['Model']['F_ora_cxzc']['FNumber'] = $info['sales_policy'] ? $info['sales_policy'] : '';//销售政策
        $arr['Model']['F_ora_ywlx']['FNumber'] = '0' . $info['business_type'];//业务类型
        $arr['Model']['F_ora_kdlx']['FNumber'] = '0' . $info['order_type'];//开单类型

        $arr['Model']['F_ora_Assistant']['FNumber'] = '0' . $info['income_type'];//收入类型
        $arr['Model']['SubHeadEntity']['FSettleOrgId']['FNumber'] = $sale_no;//销售组织
        $arr['Model']['FStockDeptId']['FNumber'] = $info['delivery_king'];//库存部门编码


        //需修改为代码获取
        $king_goods = [];
        // 根据订单id查询该订单下所有的商品存储数据
        $info['order_goods'] = Db::name('shop_refund_order_goods')
            ->where('order_id', $order_id)
            ->field('id, number, pay_price, goods_price, goods_id, kingdee_code,unit_code,is_gift,goods_deal_time,descs,house_code,is_project,data_business_type')
            ->select()
            ->toArray();
        $og_count = count($info['order_goods']);
        for ($og_i = 0; $og_i < $og_count; $og_i++) {
            //商品
            if ($info['order_goods'][$og_i]['is_project']==1)
            {
                $king_goods[$og_i]['FRowType'] = "Standard";
            }else
            {
                //服务
                $king_goods[$og_i]['FRowType'] = "Service";
            }
            $king_goods[$og_i]['FMaterialId']['FNumber'] = $info['order_goods'][$og_i]['kingdee_code']; // 商品金蝶编码
            $king_goods[$og_i]['FStockId']['FNumber'] = $shop_no; // 商品金蝶编码
            $king_goods[$og_i]['FUnitID']['FNumber'] = $info['order_goods'][$og_i]['unit_code'];//销售单位
            $king_goods[$og_i]['FRealQty'] = $info['order_goods'][$og_i]['number'];//退货数量
            $king_goods[$og_i]['FIsFree'] = $info['order_goods'][$og_i]['is_gift'] == 1 ? true : false;//是否赠品
            $king_goods[$og_i]['FOwnerTypeID'] = "BD_OwnerOrg";;
            $king_goods[$og_i]['FDeliveryDate'] = date('Y-m-d', $info['order_goods'][$og_i]['goods_deal_time']);//退货日期
            $king_goods[$og_i]['FSalUnitID']['FNumber'] = $info['order_goods'][$og_i]['unit_code'];//销售单位
            $king_goods[$og_i]['FStockId']['FNumber'] = $info['order_goods'][$og_i]['house_code'];//发货仓库编码
            //不是赠品，需要传递含税单价
            if ($info['order_goods'][$og_i]['is_gift'] < 1) {
                $king_goods[$og_i]['FPrice'] = $info['order_goods'][$og_i]['pay_price'];
                $king_goods[$og_i]['FTaxPrice'] = $info['order_goods'][$og_i]['pay_price'];
            }
            //商品
            if ($info['order_goods'][$og_i]['is_project']==1)
            {
                $king_goods[$og_i]['F_bzdj'] = $info['order_goods'][$og_i]['goods_price'];//商品取标准单价
            }else
            {
                $king_goods[$og_i]['F_bzdj'] = $info['order_goods'][$og_i]['pay_price'];//项目取销售单价
            }
            $king_goods[$og_i]['FOwnerID']['FNumber'] = $settlement_no;//货主

        }
        $arr['Model']['FEntity'] = $king_goods;

        //判断是否推运行空 begin
        $is_send_project = $is_send_product = 0;
        $business_values = array_column($info['order_goods'],'data_business_type');

        $business_values_count = array_count_values($business_values);

        if(isset($business_values_count[1]) || isset($business_values_count[2]) || isset($business_values_count[3]) ){
            $is_send_project = 1;
        }
        if(isset($business_values_count[4]) ){
            $is_send_product = 1;
        }
        //判断是否推运行空 end

        if($is_send_product == 1){
            $F_ora__hjje_apv = bcadd(0,array_sum([$info['product_gift_amount'],$info['product_pay_amount']]),2);

            $arr['Model']['F_ora__zsje_re5'] = $info['product_gift_amount'];//产品预存赠送金额
//            $arr['Model']['F_ora_Amount_apv_83g'] = $info['product_shop_transfer_amount'];  //产品转诊金额
            $arr['Model']['F_ora__xsje_qtr'] = $info['product_pay_amount'];  //产品销售金额
            $arr['Model']['F_ora__hjje_apv'] = $F_ora__hjje_apv;  //产品合计金额
            $arr['Model']['F_ora_Assistant_qtr']['FNumber'] = '02';  //产品收入类型
        }

        if($is_send_project == 1){
            $F_ora__hjje_apv_dvn = bcadd(0,array_sum([$info['project_gift_amount'],$info['project_pay_amount']]),2);
//            $arr['Model']['F_ora__zsje_re5_fg2'] = $info['project_shop_transfer_amount'];//项目预存赠送金额
            $arr['Model']['F_ora_Amount_apv_83g_uky'] = $info['project_gift_amount'];  //项目转诊金额
            $arr['Model']['F_ora__xsje_qtr_ca9'] = $info['project_pay_amount'];  //项目销售金额
            $arr['Model']['F_ora__hjje_apv_dvn'] = $F_ora__hjje_apv_dvn;  //项目合计金额
            $arr['Model']['F_ora_Assistant_83g']['FNumber'] = '01';  //项目收入类型
        }

        $data = array(
            "SAL_RETURNSTOCK",//业务对象标识FormId
            json_encode($arr)//具体Json字串
        );

        $param = $this->post();
        if ($param) {
            $post_content = KingFunction::create_postdata($data);
            $result = json_decode(KingFunction::invoke_save($param['url'], $post_content, $param['cook'],$param['session']), TRUE);
            if ($result['Result']['ResponseStatus']['IsSuccess']) {
                //成功处理
                $param = $result['Result']['ResponseStatus']['SuccessEntitys'][0];
                Db::name('shop_refund_order')->where(['id' => $order_id])->update(['king_status' => 1, 'king_id' => $param['Id'], 'king_num' => $param['Number'], 'king_push_time' => time(), 'status' => 2]);


                return ['code' => 0, 'msg' => '操作成功'];
            } else {
                // 订单下推失败 则记录该订单下推时的参数值
                $errorMsg = $result['Result']['ResponseStatus']['Errors'][0]['Message'];

                return ['code' => 1, 'msg' => $errorMsg];
            }
        } else {
            $errorMsg = 'king login error! order_id is' . $order_id;
            $this->addPushLog($info, 2, $errorMsg, $arr, $param);
            return ['code' => 1, 'msg' => '金蝶账号登录失败'];
        }
    }

    /**
     * 收款单接口
     * @param $order_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function receipt_money($order_id)
    {

        $info = Db::name('shop_refund_order')->where(['id' => $order_id])->find();
        if (!$info) {
            return ['code' => 1, 'msg' => '订单信息获取失败'];
        }

        //客户金蝶编码
        //$king_no='301.01.0325';
        $king_no = KingFunction::get_king_no($info['uid']);

        if ($king_no == '') {
            return ['code' => 1, 'msg' => '客户金蝶编码获取失败'];
        }


        //销售组织（市场编码）
        $sale_no = $info['sales_organization'];
        $settlement_no = $info['settlement_organization'];
        $shop_no = KingFunction::get_shop_no($info['shop_id']);
        if ($sale_no == '') {
            return ['code' => 1, 'msg' => '退款组织编码获取失败'];
        }
        if ($shop_no == '') {
            return ['code' => 1, 'msg' => '门店编码获取失败'];
        }
        if($shop_no == '302.02')
        {
            $customer = DB::name('customer')->where('id','=',$info['uid'])->find();
            if($customer['source_id'] == 597)
            {
                $shop_no = '302.04';
            }
        }


        $data_model = "{
    \"NeedUpDateFields\":[

    ],
    \"NeedReturnFields\":[

    ],
    \"IsDeleteEntry\":\"true\",
    \"SubSystemId\":\"\",
    \"IsVerifyBaseDataField\":\"false\",
    \"IsEntryBatchFill\":\"true\",
    \"ValidateFlag\":\"true\",
    \"NumberSearch\":\"true\",
    \"IsAutoAdjustField\":\"false\",
    \"InterationFlags\":\"\",
    \"IgnoreInterationFlag\":\"\",
    \"Model\":{
        \"FID\":0,
        \"FBillTypeID\":{
            \"FNUMBER\":\"SKDLX01_SYS\"
        },
        \"FDATE\":\"\",
        \"FCONTACTUNITTYPE\":\"BD_Customer\",
        \"FPAYUNITTYPE\":\"BD_Customer\",
        \"FCURRENCYID\":{
            \"FNumber\":\"PRE001\"
        },
        \"FPAYORGID\":{
            \"FNumber\":\"\"
        },
        \"FSETTLERATE\":1,
        \"FSETTLEORGID\":{
            \"FNumber\":\"\"
        },
        \"FSALEORGID\":{
            \"FNumber\":\"\"
        },
        \"FDOCUMENTSTATUS\":\"Z\",
        \"FBUSINESSTYPE\":\"1\",
        \"FISINIT\":false,
        \"FEXCHANGERATE\":1,
        \"FCancelStatus\":\"A\",
        \"FSETTLECUR\":{
            \"FNUMBER\":\"PRE001\"
        },
        \"FISB2C\":false,
        \"FIsWriteOff\":false,
        \"FREMARK\":\"\",
        \"F_ora_Text_re5\":\"\",
        \"FSETTLEMAINBOOKID\":{
            \"FNUMBER\":\"PRE001\"
        },
        \"FISCARRYRATE\":false,
        \"FVirIsSameAcctOrg\":false,
        \"F_ora_cxzc\":{
            \"FNumber\":\"\"
        },
        \"F_ora_kdlx\":{
            \"FNumber\":\"\"
        },
        \"F_ora_Text_re5\":{
            \"FNumber\":\"\"
        }
    }
}";
        $setting = DB::name('setting')->cache(true,3600)->column('name','id');
        $res = stripslashes($data_model);//字符串转义
        $arr = json_decode($res, true);
        $arr['Model']['FDate'] = date('Y-m-d', $info['deal_time']);//成交日期
        $arr['Model']['FPAYUNIT']['FNumber'] = $king_no;//客户编码
        $arr['Model']['FCONTACTUNIT']['FNumber'] = $king_no;//客户编码
        $arr['Model']['FPAYORGID']['FNumber'] = $settlement_no;//收款组织
        $arr['Model']['FSETTLEORGID']['FNumber'] = $sale_no;//结算组织
        $arr['Model']['FSALEORGID']['FNumber'] = $sale_no;//销售组织
        $arr['Model']['FSALEDEPTID']['FNumber'] = $shop_no;//门店编码
        $arr['Model']['FREMARK'] = $this->js_unescape($info['description']);//备注
        $arr['Model']['F_ora_Base']['FNumber'] = $king_no;//客户编码
        $arr['Model']['F_ora_Text_re5'] = isset($setting[$info['source_id']])?$setting[$info['source_id']]:'';
        $arr['Model']['F_ora_cxzc']['FNumber'] = $info['sales_policy'];//促销政策 需修改为代码获取
        $arr['Model']['F_ora_kdlx']['FNumber'] = '0' . $info['order_type'];//开单类型 需修改为代码获取
        $res=0;
        if ($settlement_no !== $sale_no)
        {
            $res=1;
        }
        //需修改为代码获取
        $king_goods = [];
        // 根据订单id查询该订单下所有的商品存储数据
        $info['refund_order_goods'] = Db::name('shop_refund_order_goods')
            ->where('order_id', $order_id)
            ->field('id, refund_mode, bank_number,data_business_type,data_sales_policy,descs,pay_price,gift_price,shop_transfer_price')
            ->select()
            ->toArray();
        $og_count = count($info['refund_order_goods']);
        for ($og_i = 0; $og_i < $og_count; $og_i++) {
            $king_goods[$og_i]['FSETTLETYPEID']['FNumber'] = $info['refund_order_goods'][$og_i]['refund_mode'];//结算方式
            $king_goods[$og_i]['FPURPOSEID']['FNumber'] = "SFKYT01_SYS";//原收款用途 SFKYT01_SYS 销售收款  SFKYT02_SYS 预收款
            $king_goods[$og_i]['FRECTOTALAMOUNTFOR'] = bcadd(bcadd($info['refund_order_goods'][$og_i]['pay_price'], $info['refund_order_goods'][$og_i]['gift_price'], 2),$info['refund_order_goods'][$og_i]['shop_transfer_price'],2);//应收金额
            $king_goods[$og_i]['FACCOUNTID']['FNumber'] = $info['refund_order_goods'][$og_i]['bank_number'];;//我方银行账号
            $king_goods[$og_i]['FSETTLEDISTAMOUNTFOR'] = $info['refund_order_goods'][$og_i]['gift_price'];//赠送金额
            $king_goods[$og_i]['F_ora_Amount_qtr'] = $info['refund_order_goods'][$og_i]['shop_transfer_price'];//店转金额

            $king_goods[$og_i]['F_ora_Aywlx']['FNumber'] = '0'.$info['refund_order_goods'][$og_i]['data_business_type'];//业务类型编码
            $king_goods[$og_i]['F_ora_Acxzc']['FNumber'] =$info['refund_order_goods'][$og_i]['data_sales_policy'];//促销政策编码
            if ($res & $sale_no=='403')
            {
                $king_goods[$og_i]['FINNERACCOUNTID']['FNUMBER'] ='888';//成都市场内部账号
            }
            if ($res & $sale_no=='401')
            {
                $king_goods[$og_i]['FINNERACCOUNTID']['FNUMBER'] ='666';//重庆市场内部账号
            }
        }

        $arr['Model']['FRECEIVEBILLENTRY'] = $king_goods;
        $data = array(
            "AR_RECEIVEBILL",//业务对象标识FormId
            json_encode($arr)//具体Json字串
        );
        //print_r(json_encode($arr));
        $param = $this->post();

        if ($param) {
            $post_content = KingFunction::create_postdata($data);
            $result = json_decode(KingFunction::invoke_save($param['url'], $post_content, $param['cook'],$param['session']), TRUE);
            if ($result['Result']['ResponseStatus']['IsSuccess']) {
                //成功处理
                $param = $result['Result']['ResponseStatus']['SuccessEntitys'][0];
                Db::name('shop_refund_order')->where(['id' => $order_id])->update(['king_status' => 1, 'king_id' => $param['Id'], 'king_num' => $param['Number'], 'king_push_time' => time(), 'status' => 2]);

                return ['code' => 0, 'msg' => '操作成功'];
            } else {
                // 订单下推失败 则记录该订单下推时的参数值
                $errorMsg = $result['Result']['ResponseStatus']['Errors'][0]['Message'];
                return ['code' => 1, 'msg' => $errorMsg];
            }
        } else {

            return ['code' => 1, 'msg' => '金蝶账号登录失败'];
        }

    }


    /**
     * 保存客户数据
     * @param array $params
     * @return false|void
     * @author Mr.Liu
     * @create 2021-10-15 16:08
     */
    public function add_customer($kingData)
    {
        $fcustId = $kingData['fcustId']; // 内码id
        $customer_name = $kingData['customer_name']; //客户名称 代码获取
        $sale_no = $kingData['sale_no']; //组织编码
        $shop_no = $kingData['shop_no'];//门店编码
        $shop_id = $kingData['shop_id'];//门店编码
        $king_no = $kingData['king_no'];//客户金蝶编码
        $customer_id = $kingData['customer_id'];//客户id
//        $params=Db::name('customer')->where(['id'=>$user_id])->find();
//        $user_id = $params['customer_id'] ?? 0; // 客户ID
//        $fcustId  = $params['king_id'] ?? 0; // 反审核后修改客户信息需要用到  201255
//        $shopName = $params['shop_name'] ?? ''; //
//        $region   = $params['region'] ?? ''; // DQ001
//        $address  = $params['address'] ?? ''; // 威科姆D座3楼
//        $tel      = $params['tel'] ?? ''; // 16666666666
//        $seller   = $params['seller'] ?? ''; //
//        $province = $params['province'] ?? ''; // 10
//        $city     = $params['city'] ?? ''; // 1001
//        $shopShortName = $params['shop_short_name'] ?? ''; // 添加客户短名称
//        if (!$user_id || !$shopName || !$region || !$address || !$tel || !$seller || !$province || !$city) {
//            return false;
//        }
        // Db::name('crm_customer_bind')->where('customer_id', '=', $user_id)->update(['king_status' => 2]);

        // 默认数据结构
        $dataModel = '{
    "NeedUpDateFields": [],
    "NeedReturnFields": [],
    "IsDeleteEntry": "true",
    "SubSystemId": "",
    "IsVerifyBaseDataField": "false",
    "IsEntryBatchFill": "true",
    "ValidateFlag": "true",
    "NumberSearch": "true",
    "IsAutoAdjustField": "false",
    "InterationFlags": "",
    "IgnoreInterationFlag": "",
    "Model": {
        "FCUSTID": 0,
        "FCreateOrgId": {
            "FNumber": "301"
        },
        "FUseOrgId": {
            "FNumber": "301"
        },
        "FCOUNTRY": {
            "FNumber": "China"
        },
        "FINVOICETITLE": "信息部测试",
        "FIsGroup": false,
        "FIsDefPayer": false,
        "FCustTypeId": {
            "FNumber": "KHLB001_SYS"
        },
        "FTRADINGCURRID": {
            "FNumber": "PRE001"
        },
        "FInvoiceType": "1",
        "FTaxType": {
            "FNumber": "SFL02_SYS"
        },
        "FPriority": 1,
        "FTaxRate": {
            "FNumber": "SL02_SYS"
        },
        "FISCREDITCHECK": true,
        "FIsTrade": true,
        "FUncheckExpectQty": false,
        "FT_BD_CUSTOMEREXT": {
            "FEnableSL": false,
            "FALLOWJOINZHJ": false
        }
    }
}';

        $res = stripslashes($dataModel);//字符串转义
        $arr = json_decode($res, true);
        // 填充需要的数据
        $arr['Model']['FNumber'] = $king_no; //金蝶客户编码
        $arr['Model']['FCUSTID'] = $fcustId ?? 0; //金蝶客户档案内联编号iud
        $arr['Model']['FName'] = $customer_name; // 客户姓名
        $arr['Model']['FCOUNTRY']['FNumber'] = 'China'; // 国家
        // $arr['Model']['FINVOICETITLE']          = $customer_name; // 发票抬头
        $arr['Model']['FCreateOrgId']['FNumber'] = $sale_no; // 组织编码
        $arr['Model']['FGroup']['FNumber'] = $shop_no; // 门店编码
        $data = array(
            "BD_Customer", // 业务对象标识FormId
            json_encode($arr) // 具体Json字串
        );
        $postParams = $this->post();

        if ($postParams) {
            $postContent = KingFunction::create_postdata($data);
            $result = json_decode(KingFunction::invoke_save($postParams['url'], $postContent, $postParams['cook'],$postParams['session']), TRUE);
            $requestData = [
                'data' => ['BD_Customer', $arr],
                'result' => $result
            ];

            if (isset($result['Result']['ResponseStatus']['IsSuccess']) && $result['Result']['ResponseStatus']['IsSuccess']) {

                //成功处理
                $res = $result['Result']['ResponseStatus']['SuccessEntitys'][0];
                $kingId = $res['Id']; // 客户内码
                $kingNo = $res['Number']; // 客户金蝶编码
                // 这里需要保存客户内码
                Db::name('customer_bind')->insert([
                    // 'king_status' => 1,
                    'shop_id' => $shop_id,
                    'fcustId' => $kingId,
                    'king_no' => $kingNo,
                    'customer_id' => $customer_id,
                ]);
                Db::name('customer')->where('id', '=', $customer_id)->update([
                    'fcustId' => $kingId,
                    'king_no' => $kingNo
                ]);

                return true;
            } else {
                $errorMsg = $result['Result']['ResponseStatus']['Errors'][0]['Message'];
                //添加日志记录
                $queueData = [];
                $queueData['king_type'] = 1;
                $queueData['log_level'] = 'fail';//日志级别
                $queueData['customer_id'] = $customer_id;
                $queueData['code'] = json_encode($requestData, JSON_UNESCAPED_UNICODE);
                $queueData['content'] = '客户 保存 金蝶，失败，' . $errorMsg;
                $queueData['create_time'] = time();
                Db::name('customer_kingdee_log')->insert($queueData);

                return $errorMsg;
            }
        } else {
            //添加日志记录
            $queueData = [];
            $queueData['king_type'] = 1;
            $queueData['log_level'] = 'fail';//日志级别
            $queueData['customer_id'] = $customer_id;
            $queueData['content'] = '金蝶登录POST失败';
            $queueData['create_time'] = time();
            Db::name('customer_kingdee_log')->insert($queueData);

            return false;
        }
    }

    /**
     * 提交客户数据
     * @param array $params
     * @return false|void
     * @author Mr.Liu
     * @create 2021-10-15 16:08
     */
    public function submit_customer($subData)
    {
        $fcustId = $subData['fcustId'];
        $customer_id = $subData['customer_id'];
        // 默认数据结构
        $dataModel = '{"Numbers":[],"Ids":"","SelectedPostId":0,"NetworkCtrl":""}';
        $res = stripslashes($dataModel);//字符串转义
        $arr = json_decode($res, true);

        // 填充需要的数据
        $arr['Ids'] = $fcustId; //金蝶客户内码 代码获取
        $data = array(
            "BD_Customer", // 业务对象标识FormId
            json_encode($arr) // 具体Json字串
        );
        $postParams = $this->post();
        if ($postParams) {
            $postContent = KingFunction::create_postdata($data);
            $result = json_decode(KingFunction::invoke_submit($postParams['url'], $postContent, $postParams['cook'], $postParams['session']), TRUE);

            // 记录推送金蝶数据
            $requestData = [
                'data' => ['BD_Customer', $arr],
                'result' => $result
            ];
            //添加日志记录
            $queueData = [];
            $queueData['king_type'] = 2;
            $queueData['log_level'] = 'info';//日志级别
            $queueData['customer_id'] = $customer_id;
            $queueData['code'] = json_encode($requestData, JSON_UNESCAPED_UNICODE);
            $queueData['content'] = '请求 invoke_submit';
            $queueData['create_time'] = time();
            Db::name('customer_kingdee_log')->insert($queueData);

            // print_r(json_encode($result, JSON_UNESCAPED_UNICODE));
            if (!$result || !is_array($result)) {
                //添加日志记录
                $queueData = [];
                $queueData['king_type'] = 2;
                $queueData['log_level'] = 'fail';//日志级别
                $queueData['customer_id'] = $customer_id;
                $queueData['code'] = json_encode($requestData, JSON_UNESCAPED_UNICODE);
                $queueData['content'] = '请求 invoke_submit，失败';
                $queueData['create_time'] = time();
                Db::name('customer_kingdee_log')->insert($queueData);

                return false;
            }
            if (isset($result['Result']['ResponseStatus']['IsSuccess']) && $result['Result']['ResponseStatus']['IsSuccess']) {
                //添加日志记录
                $queueData = [];
                $queueData['king_type'] = 2;
                $queueData['log_level'] = 'success';//日志级别
                $queueData['customer_id'] = $customer_id;
                $queueData['code'] = json_encode($requestData, JSON_UNESCAPED_UNICODE);
                $queueData['content'] = '客户 提交 金蝶，成功';
                $queueData['create_time'] = time();
                Db::name('customer_kingdee_log')->insert($queueData);

                //成功处理
                // Db::name('crm_customer_bind')->where('customer_id', '=', $user_id)->update(['king_status' => 3]);

                return true;
            } else {
                $errorMsg = $result['Result']['ResponseStatus']['Errors'][0]['Message'];
                //添加日志记录
                $queueData = [];
                $queueData['king_type'] = 2;
                $queueData['log_level'] = 'fail';//日志级别
                $queueData['customer_id'] = $customer_id;
                $queueData['code'] = json_encode($requestData, JSON_UNESCAPED_UNICODE);
                $queueData['content'] = '客户 提交 金蝶，失败，' . $errorMsg;
                $queueData['create_time'] = time();
                Db::name('customer_kingdee_log')->insert($queueData);

                return $errorMsg;
            }
        } else {
            //添加日志记录
            $queueData = [];
            $queueData['king_type'] = 2;
            $queueData['log_level'] = 'fail';//日志级别
            $queueData['customer_id'] = $customer_id;
            $queueData['content'] = '金蝶登录POST失败';
            $queueData['create_time'] = time();
            Db::name('customer_kingdee_log')->insert($queueData);

            return false;
        }
    }

    /**
     * 审核客户数据
     * @param array $params
     * @return false|void
     * @author Mr.Liu
     * @create 2021-10-15 16:08
     */
    public function audit_customer($auditData)
    {
//        $user_id = $params['customer_id'] ?? 0; // 客户ID
//        $info       = Db::name('crm_customer_bind')->where('customer_id', '=', $user_id)->find();
//        if (!$user_id || !$info) {
//            //添加日志记录
//            $queueData                = [];
//            $queueData['king_type']   = 3;
//            $queueData['log_level']   = 'fail';//日志级别
//            $queueData['customer_id'] = $user_id;
//            $queueData['content']     = '参数错误';
//            $queueData['code']        = json_encode( $params, JSON_UNESCAPED_UNICODE );
//            customer_kingdee_log_queue($queueData);
//
//            return false;
//        }
        $fcustId = $auditData['fcustId'];
        $customer_id = $auditData['customer_id'];
        // $fcustId = $info['king_id'] ?: 0;
//        Db::name('crm_customer_bind')->where('customer_id', '=', $user_id)->update(['king_status' => 6]);
//        if (!$fcustId) {
//            return false;
//        }

        // 默认数据结构
        $dataModel = '{"Numbers":[],"Ids":"","InterationFlags":"","NetworkCtrl":""}';
        $res = stripslashes($dataModel);//字符串转义
        $arr = json_decode($res, true);

        // 填充需要的数据
        $arr['Ids'] = $fcustId; //金蝶客户内码
        $data = array(
            "BD_Customer", // 业务对象标识FormId
            json_encode($arr) // 具体Json字串
        );
        $postParams = $this->post();
        if ($postParams) {
            $postContent = KingFunction::create_postdata($data);
            $result = json_decode(KingFunction::invoke_audit($postParams['url'], $postContent, $postParams['cook'],$postParams['session']), TRUE);
            // var_dump($result);exit;
            // 记录推送金蝶数据
            $requestData = [
                'data' => ['BD_Customer', $arr],
                'result' => $result
            ];
            //添加日志记录
            $queueData = [];
            $queueData['king_type'] = 3;
            $queueData['log_level'] = 'info';//日志级别
            $queueData['customer_id'] = $customer_id;
            $queueData['code'] = json_encode($requestData, JSON_UNESCAPED_UNICODE);
            $queueData['content'] = '请求 invoke_audit';
            $queueData['create_time'] = time();
            Db::name('customer_kingdee_log')->insert($queueData);


            // print_r(json_encode($result, JSON_UNESCAPED_UNICODE));
            if (!$result || !is_array($result)) {
                //添加日志记录
                $queueData = [];
                $queueData['king_type'] = 3;
                $queueData['log_level'] = 'fail';//日志级别
                $queueData['customer_id'] = $customer_id;
                $queueData['code'] = json_encode($requestData, JSON_UNESCAPED_UNICODE);
                $queueData['content'] = '请求 invoke_audit，失败';
                $queueData['create_time'] = time();
                Db::name('customer_kingdee_log')->insert($queueData);


                return false;
            }
            if (isset($result['Result']['ResponseStatus']['IsSuccess']) && $result['Result']['ResponseStatus']['IsSuccess']) {
                //添加日志记录
                $queueData = [];
                $queueData['king_type'] = 3;
                $queueData['log_level'] = 'success';//日志级别
                $queueData['customer_id'] = $customer_id;
                $queueData['code'] = json_encode($requestData, JSON_UNESCAPED_UNICODE);
                $queueData['content'] = '客户 审核 金蝶，成功';
                $queueData['create_time'] = time();
                Db::name('customer_kingdee_log')->insert($queueData);

                //成功处理
                // Db::name('crm_customer_bind')->where('customer_id', '=', $user_id)->update(['king_status' => 5]);

                return true;
            } else {
                $errorMsg = $result['Result']['ResponseStatus']['Errors'][0]['Message'];
                //添加日志记录
                $queueData = [];
                $queueData['king_type'] = 3;
                $queueData['log_level'] = 'fail';//日志级别
                $queueData['customer_id'] = $customer_id;
                $queueData['code'] = json_encode($requestData, JSON_UNESCAPED_UNICODE);
                $queueData['content'] = '客户 审核 金蝶，失败，' . $errorMsg;
                $queueData['create_time'] = time();
                Db::name('customer_kingdee_log')->insert($queueData);

                return $errorMsg;
            }
        } else {
            //添加日志记录
            $queueData = [];
            $queueData['king_type'] = 3;
            $queueData['log_level'] = 'fail';//日志级别
            $queueData['customer_id'] = $customer_id;
            $queueData['content'] = '金蝶登录POST失败';
            $queueData['create_time'] = time();
            Db::name('customer_kingdee_log')->insert($queueData);

            return false;
        }
    }


    /**
     * 反审核客户数据
     * @param array $params
     * @return false|void
     * @author Mr.Liu
     * @create 2021-10-15 16:08
     */
    public function again_audit_customer($user_id)
    {

        $fcustId = "238481";

        // 默认数据结构
        $dataModel = '{"Numbers":[],"Ids":"","InterationFlags":"","NetworkCtrl":""}';
        $res = stripslashes($dataModel);//字符串转义
        $arr = json_decode($res, true);

        // 填充需要的数据
        $arr['Ids'] = $fcustId; //金蝶客户内码
        $data = array(
            "BD_Customer", // 业务对象标识FormId
            json_encode($arr) // 具体Json字串
        );
        $postParams = $this->post();
        if ($postParams) {
            $postContent = KingFunction::create_postdata($data);
            $result = json_decode(KingFunction::invoke_un_audit($postParams['url'], $postContent, $postParams['cook'],$postParams['session']), TRUE);
            // var_dump($result);
            // exit;
            // 记录推送金蝶数据
            $requestData = [
                'data' => ['BD_Customer', $arr],
                'result' => $result
            ];
            //添加日志记录
            $queueData = [];
            $queueData['king_type'] = 6;
            $queueData['log_level'] = 'info';//日志级别
            $queueData['customer_id'] = $user_id;
            $queueData['code'] = json_encode($requestData, JSON_UNESCAPED_UNICODE);
            $queueData['content'] = '请求 invoke_un_audit';
            customer_kingdee_log_queue($queueData);

            // print_r(json_encode($result, JSON_UNESCAPED_UNICODE));
            if (!$result || !is_array($result)) {
                //添加日志记录
                $queueData = [];
                $queueData['king_type'] = 6;
                $queueData['log_level'] = 'fail';//日志级别
                $queueData['customer_id'] = $user_id;
                $queueData['code'] = json_encode($requestData, JSON_UNESCAPED_UNICODE);
                $queueData['content'] = '请求 invoke_un_audit，失败';
                customer_kingdee_log_queue($queueData);

                return false;
            }
            if (isset($result['Result']['ResponseStatus']['IsSuccess']) && $result['Result']['ResponseStatus']['IsSuccess']) {
                //添加日志记录
                $queueData = [];
                $queueData['king_type'] = 6;
                $queueData['log_level'] = 'success';//日志级别
                $queueData['customer_id'] = $user_id;
                $queueData['code'] = json_encode($requestData, JSON_UNESCAPED_UNICODE);
                $queueData['content'] = '客户 反审核 金蝶，成功';
                customer_kingdee_log_queue($queueData);

                //成功处理
                Db::name('crm_customer_bind')->where('customer_id', '=', $user_id)->update(['king_again_audit' => 1]);

                return true;
            } else {
                $errorMsg = $result['Result']['ResponseStatus']['Errors'][0]['Message'];
                //添加日志记录
                $queueData = [];
                $queueData['king_type'] = 6;
                $queueData['log_level'] = 'fail';//日志级别
                $queueData['customer_id'] = $user_id;
                $queueData['code'] = json_encode($requestData, JSON_UNESCAPED_UNICODE);
                $queueData['content'] = '客户 反审核 金蝶，失败，' . $errorMsg;
                customer_kingdee_log_queue($queueData);

                return false;
            }
        } else {
            //添加日志记录
            $queueData = [];
            $queueData['king_type'] = 6;
            $queueData['log_level'] = 'fail';//日志级别
            $queueData['customer_id'] = $user_id;
            $queueData['content'] = '金蝶登录POST失败';
            customer_kingdee_log_queue($queueData);

            return false;
        }
    }


    /**
     * 禁用启用
     * @param array $params
     * @return false|void
     * @author Mr.Liu Wuchen
     * @create 2021-10-15 16:08
     */
    public function forbid_customer($user_id)
    {

        $forbidNameArr = ['1' => '启用', '2' => '禁用'];
        $info = Db::name('crm_customer')->where('customer_id', '=', $user_id)->find();
        if (empty($info)) {
            return false;
        }
        Db::name('crm_customer')->where('customer_id', '=', $user_id)->update(['king_forbid_status' => 2]);
        $forbidName = $forbidNameArr[$info['king_status']];

        // 默认数据结构
        $dataModel = '{"Numbers":[],"Ids":"","PkEntryIds":[],"NetworkCtrl":""}';
        $res = stripslashes($dataModel);//字符串转义
        $arr = json_decode($res, true);
        $fcustId = "238481";
        // 客户启用禁用
        $forbidKey = $info['king_forbid_status'] == 1 ? 'Enable' : 'Forbid';

        // 填充需要的数据
        $arr['Ids'] = $fcustId; //金蝶客户内码
        $data = array(
            "BD_Customer", // 业务对象标识FormId
            $forbidKey,
            json_encode($arr) // 具体Json字串
        );
        $postParams = $this->post();
        if ($postParams) {

            $postContent = KingFunction::create_postdata($data);
            $result = json_decode(KingFunction::invoke_operation($postParams['url'], $postContent, $postParams['cook'], $postParams['session']), TRUE);

            // 记录推送金蝶数据
            $requestData = [
                'data' => ['BD_Customer', $forbidKey, $arr],
                'result' => $result
            ];
            var_dump($result);
            exit;
            //添加日志记录
            $queueData = [];
            $queueData['king_type'] = 7;
            $queueData['log_level'] = 'info';//日志级别
            $queueData['customer_id'] = $user_id;
            $queueData['code'] = json_encode($requestData, JSON_UNESCAPED_UNICODE);
            $queueData['content'] = $forbidName . '请求 invoke_operation';
            customer_kingdee_log_queue($queueData);

            // print_r(json_encode($result, JSON_UNESCAPED_UNICODE));
            if (!$result || !is_array($result)) {
                //添加日志记录
                $queueData = [];
                $queueData['king_type'] = 7;
                $queueData['log_level'] = 'fail';//日志级别
                $queueData['customer_id'] = $user_id;
                $queueData['code'] = json_encode($requestData, JSON_UNESCAPED_UNICODE);
                $queueData['content'] = $forbidName . '请求 invoke_operation，失败';
                customer_kingdee_log_queue($queueData);

                return false;
            }

            // 这里为了处理金蝶和数据库客户状态不一致问题
            $msgBool = false;
            $errorMsg = $result['Result']['ResponseStatus']['Errors'][0]['Message'] ?? '';
            if (strpos($errorMsg, '未禁用') !== false || strpos($errorMsg, '已经禁用') !== false) {
                $msgBool = true;
            }

            if ((isset($result['Result']['ResponseStatus']['IsSuccess']) && $result['Result']['ResponseStatus']['IsSuccess']) || $msgBool) {
                //添加日志记录
                $queueData = [];
                $queueData['king_type'] = 7;
                $queueData['log_level'] = 'success';//日志级别
                $queueData['customer_id'] = $user_id;
                $queueData['code'] = json_encode($requestData, JSON_UNESCAPED_UNICODE);
                $queueData['content'] = $forbidName . '客户金蝶，成功';
                customer_kingdee_log_queue($queueData);

                //成功处理
                Db::name('crm_customer_bind')->where('customer_id', '=', $customerId)->update(['king_forbid_status' => 1]);

                return true;
            } else {
                $errorMsg = $result['Result']['ResponseStatus']['Errors'][0]['Message'];
                //添加日志记录
                $queueData = [];
                $queueData['king_type'] = 7;
                $queueData['log_level'] = 'fail';//日志级别
                $queueData['customer_id'] = $user_id;
                $queueData['code'] = json_encode($requestData, JSON_UNESCAPED_UNICODE);
                $queueData['content'] = $forbidName . '客户金蝶，失败，' . $errorMsg;
                customer_kingdee_log_queue($queueData);

                return false;
            }
        } else {
            //添加日志记录
            $queueData = [];
            $queueData['king_type'] = 7;
            $queueData['log_level'] = 'fail';//日志级别
            $queueData['customer_id'] = $user_id;
            $queueData['content'] = $forbidName . '金蝶登录POST失败';
            customer_kingdee_log_queue($queueData);

            return false;
        }
    }


    /**
     * 金蝶登录
     *
     */
    public function post()
    {
        $cloudUrl = $this->king['url'];
        //登陆参数
        $data = array(
            $this->king['id'],//帐套Id
            $this->king['admin'],//用户名
            $this->king['pwd'],//密码
            2052//语言标识
        );
        // var_dump($data);
        // echo "<br/>";
        //定义记录Cloud服务端返回的Session
        //$cookie_jar = tempnam('./public/static/tmp','CloudSession');
        $post_content = KingFunction::create_postdata($data);
        // var_dump($post_content);
        // echo "<br/>";
        $result = KingFunction::invoke_login($cloudUrl, $post_content, '');
        // var_dump($result);
        // exit;
        // 解析HTTP数据流
        list($header, $body) = explode("\r\n\r\n", $result);

        // 解析COOKIE
        preg_match("/set\-cookie:([^\r\n]*)/i", $header, $matches);
        // 后面用CURL提交的时候可以直接使用
        //获取cookie
        $cookie = $matches[1];

        $array = json_decode($body, true);

        if ($array['LoginResultType'] == 1) {
            return ['url' => $cloudUrl, 'cook' => $cookie,'session'=>$array['KDSVCSessionId']];
        } else {
            Log::info('login error: return error data' . json_encode($result));
            return false;
        }

    }


    //编码转汉字
    public function js_unescape($str)
    {
        $ret = '';
        $len = strlen($str);
        for ($i = 0; $i < $len; $i++) {
            if ($str[$i] == '%' && $str[$i + 1] == 'u') {
                $val = hexdec(substr($str, $i + 2, 4));
                if ($val < 0x7f) $ret .= chr($val);
                else if ($val < 0x800) $ret .= chr(0xc0 | ($val >> 6)) . chr(0x80 | ($val & 0x3f));
                else $ret .= chr(0xe0 | ($val >> 12)) . chr(0x80 | (($val >> 6) & 0x3f)) . chr(0x80 | ($val & 0x3f));
                $i += 5;
            } else if ($str[$i] == '%') {
                $ret .= urldecode(substr($str, $i, 3));
                $i += 2;
            } else $ret .= $str[$i];
        }
        return $ret;
    }

    /**
     * 记录订单下推信息
     * @param $order_info
     * @param $status
     * @param string $msg
     * @param string $param
     * @param string $content
     * @return bool|int|string
     */
    public function addPushLog($order_info, $status, $msg = '', $param = '', $content = '')
    {
        $insertData = [
            'customer_id' => !empty($order_info) ? $order_info['uid'] : 0,
            'order_id' => !empty($order_info) ? $order_info['id'] : 0,
            'status' => $status,
            'content' => $content != '' ? json_encode($content) : '', // 下推返回的结果
            'param' => $param != '' ? json_encode($param) : '', // 下推时发送的参数
            'error_msg' => $msg, // 错误信息
            'create_time' => time(),
        ];

        return Db::name('crm_push_log')->insert($insertData);
    }

    /**
     * 根据销售出库单号获取销售出库单数据
     */
    public function get_sale_order($king_sale_no)
    {
        $sale_no = explode(',', $king_sale_no);
        $arr = [];
        foreach ($sale_no as $k => $v) {
            $res = $this->select_sale_order($v);

            if (count($res) > 0) {
                $arr[$k]['FEntity_Link_FSBillId'] = isset($res['bill']) ? $res['bill'] : '';
                $arr[$k]['FEntity_Link_FSId'] = isset($res['SId']) ? $res['SId'] : '';
                $arr[$k]['FEntity_Link_FSTableName'] = "T_SAL_OUTSTOCKENTRY";
                $arr[$k]['FEntity_Link_FRuleId'] = "OutStock-SalReturnNotice";
            }
            unset($res);
        }
        $data = [];
        $data['list'] = $arr ?? [];
        $data['dataCount'] = count($arr) ?? 0;
        return $data;
    }

    public function select_sale_order($sale_no, $no = '', $unit = '')
    {
        if (empty($sale_no)) {
            return [];
        }
        $data_model = "{\"CreateOrgId\":\"0\",\"Number\":\"\",\"Id\":\"\"}";
        $arr = json_decode(stripslashes($data_model), true);
        $arr['Number'] = $sale_no;

        $data = array(
            "SAL_OUTSTOCK",//业务对象标识FormId
            json_encode($arr)//具体Json字串
        );
        $param = $this->post();
        if ($param) {
            $post_content = KingFunction::create_postdata($data);
            $result = json_decode(KingFunction::invoke_view($param['url'], $post_content, $param['cook']), TRUE);
            if ($result['Result']['ResponseStatus'] !== NULL) {
                $res = $result['Result']['Result']['SAL_OUTSTOCKENTRY'];
                $row = [];
                if (empty($no) && empty($unit)) {
                    foreach ($res as $k => $v) {
                        $row[$k]['sku'] = $v['MaterialID']['Number'];
                        // $row[$k]['unit']=$v['UnitID']['Number'];
                        $row[$k]['num'] = $v['RealQty'];
                        $row[$k]['base_num'] = round((KingFunction::trans_unit($v['UnitID']['Number'], 0) * $v['RealQty']), 4);//基本单位数量
                        $row[$k]['store_num'] = round((KingFunction::trans_unit($v['UnitID']['Number'], 1) * $v['RealQty']), 4);//库存单位数量
                    }
                    return $row;
                }

                foreach ($res as $k => $v) {
                    if ($v['MaterialID']['Number'] == $no && $v['UnitID']['Number'] == $unit) {
                        $row['bill'] = $result['Result']['Result']['Id'];
                        $row['sku'] = $v['MaterialID']['Number'];
                        $row['unit'] = $v['UnitID']['Number'];
                        $row['num'] = $v['RealQty'];
                        $row['SId'] = $v['Id'];
                    }
                }
                return $row;
            }
        } else {
            return false;
        }
    }

}
